package controller

import (
	"github.com/gin-gonic/gin"
	"guliedu/model"
	"net/http"
	"strconv"
)

type bannerInfo struct {
	ImageUrl string `json:"imageUrl"`
	LinkUrl  string `json:"linkUrl"`
	Sort     int    `json:"sort"`
	Title    string `json:"title"`
}

func DeleteBanner(ctx *gin.Context) {
	id := ctx.Param("id")
	crmBannerServive.Delete(id)
	ctx.JSON(http.StatusOK, gin.H{
		"code": 20000,
	})
	return
}

func UpdateBanner(ctx *gin.Context) {
	banner := &bannerInfo{}
	ctx.ShouldBind(&banner)
	id := ctx.Param("id")

	b, _ := crmBannerServive.Select(id)
	b.Title = banner.Title
	b.ImageUrl = banner.ImageUrl
	b.LinkUrl = banner.LinkUrl
	b.Sort = banner.Sort
	crmBannerServive.Update(b)
	ctx.JSON(http.StatusOK, gin.H{
		"code": 20000,
	})
	return
}

func GetBannerListPage(ctx *gin.Context) {
	page := ctx.Param("page")
	pageSize := ctx.Param("pageSize")
	pageInt, _ := strconv.Atoi(page)
	pageSizeInt, _ := strconv.Atoi(pageSize)
	total, _ := crmBannerServive.SelectCount()
	banners, _ := crmBannerServive.GetBannerListPage(pageInt, pageSizeInt)
	ctx.JSON(http.StatusOK, gin.H{
		"code":  20000,
		"total": total,
		"data":  banners,
	})
	return
}

func AddBanner(ctx *gin.Context) {
	banner := &bannerInfo{}
	ctx.ShouldBind(&banner)

	b := &model.CrmBanner{
		Title:    banner.Title,
		ImageUrl: banner.ImageUrl,
		LinkUrl:  banner.LinkUrl,
		Sort:     banner.Sort,
	}
	crmBannerServive.Insert(b)
	ctx.JSON(http.StatusOK, gin.H{
		"code": 20000,
	})
	return
}

func GetAllBanner(ctx *gin.Context) {
	banners := crmBannerServive.GetCacheBanner()
	if len(banners) < 1 {
		banners, _ = crmBannerServive.SelectAll()
		crmBannerServive.CacheBanner(banners)
		ctx.JSON(http.StatusOK, gin.H{
			"code": 20000,
			"data": banners,
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": 20000,
		"data": banners,
	})
	return
}

func UploadBanner(ctx *gin.Context) {
	file, header, _ := ctx.Request.FormFile("file")
	url, _ := crmBannerServive.UploadBanner(file, header.Size)
	ctx.JSON(http.StatusOK, gin.H{
		"code": 20000,
		"data": url,
	})
	return
}

func GetBanner(ctx *gin.Context) {
	id := ctx.Param("id")
	banner, _ := crmBannerServive.Select(id)
	ctx.JSON(http.StatusOK, gin.H{
		"code": 20000,
		"data": banner,
	})
	return
}
